<?php

namespace App\Ant\Jobs;

use App\Models\Company\Archive;
use App\Models\System\Region;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Collection;
use Overtrue\Pinyin\Pinyin;

class ArchiveImportJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务最大尝试次数。
     *
     * @var int
     */
    public $tries = 5;

    /**
     * 任务运行的超时时间。
     *
     * @var int
     */
    public $timeout = 600;

    protected $items;

    /**
     * 创建一个新的任务实例。
     *
     * @return void
     */
    public function __construct(Collection $collection)
    {
        $this->items = $collection;
    }

    /**
     * 运行任务。
     *
     * @return void
     */
    public function handle()
    {
        $this->items->each(function ($item) {
            $city = $this->isRegion($item);
            $data = [
                'name'           => $item['企业名称'],
                'region_id'      => $city->id,
                'type'           => $item['企业类型'],
                'business_scope' => $item['经营范围'],
                'location'       => $item['地址'],
                'credit_code'    => $item['统一社会信用代码'],
                'legal_person'   => $item['法定代表人'],
                'established_at' => $item['成立日期'],
                'capital'        => $item['注册资本'],
                'email'          => $item['邮箱'],
                'tel'            => $item['电话号码'],
                'more_tel'       => $item['电话号码（更多号码）'],
                'website'        => $item['网址'],
                'task_id'        => $item['任务ID'],
                'is_state'       => false
            ];
            $archive = new Archive($data);
            $archive->save();
        });
    }

    protected function isRegion($item)
    {
        $province = Region::where('name', 'like', '%' . $item['省份'])->where('level', 1)->first();
        if ($province == null) {
            $province = $this->addRegion($item['省份'], 1, '');
        }
        $city = Region::where('name', 'like', '%' . $item['城市'])->where('level', 2)->first();
        if ($city == null) {
            $city = $this->addRegion($item['城市'], 2, $province->id);
        }
        return $city;
    }

    protected function addRegion($name, $level, $parent_id = null)
    {
        $region = new Region();
        $region->fill([
            'name'      => $name,
            'level'     => $level,
            'parent_id' => $parent_id,
            'initials'  => $this->pinYin($name)
        ]);
        $region->save();
    }

    private function pinYin(string $name)
    {
        $pinyin = new Pinyin();
        return $pinyin->permalink($name, '');
    }

}